package cn.xxy.result;

import cn.xxy.RowProcessor;
import cn.xxy.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author xxy
 * @date 2021/7/29
 */
public class BeanMapHandler<K, V> extends  org.apache.commons.dbutils.handlers.AbstractKeyedHandler<K, V> implements ResultSetHandler<Map<K, V>> {

    private final Class<V> beanClass;
    private final int columnIndex;
    private final String columnName;

    public BeanMapHandler(Class<V> type) {
        this(type, 1, (String)null);
    }

    public BeanMapHandler(Class<V> type, int columnIndex) {
        this(type, columnIndex, (String)null);
    }

    private BeanMapHandler(Class<V> type, int columnIndex, String columnName) {
       this.beanClass= type;
        this.columnIndex = columnIndex;
        this.columnName = columnName;
    }

    public BeanMapHandler(Class<V> type, String columnName) {
        this(type,1, columnName);
    }

    protected K createKey(ResultSet resultSet) throws SQLException {
        return (K)(this.columnName == null ? resultSet.getObject(this.columnIndex) : resultSet.getObject(this.columnName));
    }

    protected V createRow(ResultSet resultSet) throws SQLException {
        //return (V)this.convert.toBean(resultSet, this.type);
        return resultSet.next() ? RowProcessor.toBean(resultSet, beanClass) : null;
    }
}
